package pic

import (
	"errors"
	"github.com/nfnt/resize"
	"golang.org/x/image/bmp"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io"
	"os"
	"strings"
)

func ImageCompress(forigin, temp io.Reader, format, out string, base, Quality int) (err error) {
	format = strings.ToLower(format)
	var origin image.Image
	var config2 image.Config
	switch format {
	case "jpg", "jpeg":
		origin, err = jpeg.Decode(forigin)
		config2, err = jpeg.DecodeConfig(temp)
		if err != nil {
			return err
		}
	case "png":
		origin, err = png.Decode(forigin)
		config2, err = png.DecodeConfig(temp)
		if err != nil {
			return err
		}
	case "gif":
		origin, err = gif.Decode(forigin)
		config2, err = gif.DecodeConfig(temp)
		if err != nil {
			return err
		}
	case "bmp":
		origin, err = bmp.Decode(forigin)
		config2, err = bmp.DecodeConfig(temp)
		if err != nil {
			return err
		}
	}
	/** 做等比缩放 */
	width := uint(base) /** 基准 */
	height := uint(base * config2.Height / config2.Width)

	canvas := resize.Thumbnail(width, height, origin, resize.Lanczos3)
	fileOut, err := os.Create(out)
	if err != nil {
		return err
	}
	defer fileOut.Close()
	switch format {
	case "jpg", "jpeg":
		err = jpeg.Encode(fileOut, canvas, &jpeg.Options{Quality: Quality})
		if err != nil {
			return errors.New("压缩图片失败")
		}
	case "png":
		err = png.Encode(fileOut, canvas)
		if err != nil {
			return errors.New("压缩图片失败")
		}
	case "gif":
		err = gif.Encode(fileOut, canvas, &gif.Options{})
		if err != nil {
			return errors.New("压缩图片失败")
		}
	case "bmp":
		err = png.Encode(fileOut, canvas)
		if err != nil {
			return errors.New("压缩图片失败")
		}
	}
	return
}
